package com.supersit.GZFDA.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.supersit.GZFDA.R;
import com.supersit.GZFDA.adapter.BusinessListAdapter;
import com.supersit.GZFDA.db.LoadDBData;
import com.supersit.GZFDA.entity.Business;
import com.supersit.GZFDA.util.AppManager;
import com.supersit.GZFDA.util.AppUtils;
import com.supersit.GZFDA.util.ShowWindows;
import com.supersit.GZFDA.util.ShowWindows.Callback;
import com.zhy.autolayout.AutoLayoutActivity;

public class AddressSearch extends AutoLayoutActivity implements Callback {
	private EditText etFuzzySearch;
	private Button btnSearch;
	private Context context;
	private ListView lvBusiness;
	private List<Business> businessList;
	private ProgressDialog pd;
	private BusinessListAdapter adapter;
	private ImageButton ibMore;
	private TextView tvDataNum;
	private LinearLayout llDataNum;

	@Override
	protected void onCreate(@Nullable Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_search_index);
		AppManager.getAppManager().addActivity(AddressSearch.this);
		context = this;
		initView();
		bindData();
		bindListener();
		updateInfo();
	}

	private void bindListener() {
		// TODO Auto-generated method stub
		btnSearch.setOnClickListener(onClickListener);
		lvBusiness.setOnItemClickListener(onItemClickListener);
		ibMore.setOnClickListener(onClickListener);
	}

	private void initView() {
		// TODO Auto-generated method stub
		etFuzzySearch = (EditText) findViewById(R.id.et_search_street);
		btnSearch = (Button) findViewById(R.id.btn_search);
		lvBusiness = (ListView) findViewById(R.id.lv_search_data_list);
		ibMore = (ImageButton) findViewById(R.id.ib_more);
		tvDataNum = (TextView) findViewById(R.id.tv_show_data_num);
		llDataNum = (LinearLayout) findViewById(R.id.ll_show_data_num);

	}

	private void bindData() {
		businessList = startSearch();
		adapter = new BusinessListAdapter(businessList, context);
		lvBusiness.setAdapter(adapter);
	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			switch (arg0.getId()) {
			case R.id.btn_search:
				if (!TextUtils.isEmpty(etFuzzySearch.getText().toString()
						.trim())) {
					searchAddress(etFuzzySearch.getText().toString().trim());
				} else {
					businessList.clear();
					List<Business> list = startSearch();
					adapter.setBusinesss(list);
					adapter.notifyDataSetChanged();
				}
				break;
			case R.id.ib_more:
				ShowWindows sw = new ShowWindows(context, AddressSearch.this);
				sw.showPopupWindow(ibMore);
			default:
				break;
			}
		}
	};
	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(context, MainActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("type", "business");
			bundle.putSerializable("Business", adapter.getBusinesss().get(arg2));
			intent.putExtras(bundle);
			startActivity(intent);
		}
	};

	private void searchAddress(String constraint) {
		SQLiteDatabase db = LoadDBData.openDatabase(getApplicationContext());

		String selection = "select * from gzfad_data where operate_address like '%"
				+ constraint.trim() + "%' order by operate_address";
		Cursor cursor = db.rawQuery(selection, null);

		pd = ProgressDialog.show(context, "", "...正在搜索数据...");
		List<Business> list = new ArrayList<Business>();
		while (cursor.moveToNext()) {
			Business business = new Business();
			business.setId(cursor.getString(cursor.getColumnIndex("id")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("id")));
			business.setBusiness_name(cursor.getString(cursor
					.getColumnIndex("business_name")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("business_name")));
			business.setBusiness_type(cursor.getString(cursor
					.getColumnIndex("business_type")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("business_type")));
			business.setContacts(cursor.getString(cursor
					.getColumnIndex("contacts")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("contacts")));
			business.setData_of_issue(cursor.getString(cursor
					.getColumnIndex("date_of_issue")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("date_of_issue")));
			business.setExpiry_data(cursor.getString(cursor
					.getColumnIndex("expiry_date")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("expiry_date")));
			business.setLegal_person(cursor.getString(cursor
					.getColumnIndex("legal_person")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("legal_person")));
			business.setLicense_key(cursor.getString(cursor
					.getColumnIndex("license_key")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("license_key")));
			business.setOperate_addrress(cursor.getString(cursor
					.getColumnIndex("operate_address")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("operate_address")));
			business.setQuality_principal(cursor.getString(cursor
					.getColumnIndex("quality_principal")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("quality_principal")));
			business.setRange(cursor.getString(cursor.getColumnIndex("range")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("range")));
			business.setRegister_address(cursor.getString(cursor
					.getColumnIndex("register_address")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("register_address")));
			business.setStreet(cursor.getString(cursor.getColumnIndex("street")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("street")));
			business.setIsUpload(cursor.getString(cursor
					.getColumnIndex("is_upload")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("is_upload")));
			if (!("-1".equals(business.getIsUpload()))) {
				list.add(business);
			}
		}
		pd.dismiss();
		cursor.close();
		db.close();
		if (list != null && list.size() > 0) {
			llDataNum.setVisibility(View.VISIBLE);
			tvDataNum.setText("共搜索到" + list.size() + "条数据");
			businessList.clear();
			adapter.setBusinesss(list);
			adapter.notifyDataSetChanged();
		} else {
			adapter.clearList();
			adapter.notifyDataSetChanged();
			tvDataNum.setText("共搜索到0条数据");
			Toast.makeText(
					context,
					"没有搜索到\"" + etFuzzySearch.getText().toString().trim()
							+ "\"相关的数据", 1).show();
		}

	}

	/**
	 * 开始的时候就进行搜索，显示20条
	 * 
	 * @return
	 */
	private List<Business> startSearch() {
		SQLiteDatabase db = LoadDBData.openDatabase(getApplicationContext());
		String selectionSql = "select * from gzfad_data where is_upload = 0 limit 20";

		Cursor cursor = db.rawQuery(selectionSql, null);
		List<Business> list = new ArrayList<Business>();
		while (cursor.moveToNext()) {
			Business business = new Business();
			String id;
			String business_name;
			String license_key;
			String register_address;
			String operate_address;
			String contacts;
			String legal_person;
			String busi;
			String quality_principal;
			String range;
			String expiry_data;
			String data_of_issue;
			String street;
			String business_type;
			String isUpload;
			id = cursor.getString(cursor.getColumnIndex("id")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("id"));
			business_name = cursor.getString(cursor
					.getColumnIndex("business_name")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("business_name"));
			license_key = cursor
					.getString(cursor.getColumnIndex("license_key")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("license_key"));
			register_address = cursor.getString(cursor
					.getColumnIndex("register_address")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("register_address"));
			operate_address = cursor.getString(cursor
					.getColumnIndex("operate_address")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("operate_address"));
			contacts = cursor.getString(cursor.getColumnIndex("contacts")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("contacts"));
			legal_person = cursor.getString(cursor
					.getColumnIndex("legal_person")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("legal_person"));
			busi = cursor.getString(cursor.getColumnIndex("busi")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("busi"));
			quality_principal = cursor.getString(cursor
					.getColumnIndex("quality_principal")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("quality_principal"));
			range = cursor.getString(cursor.getColumnIndex("range")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("range"));
			expiry_data = cursor
					.getString(cursor.getColumnIndex("expiry_date")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("expiry_date"));
			data_of_issue = cursor.getString(cursor
					.getColumnIndex("date_of_issue")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("date_of_issue"));
			street = cursor.getString(cursor.getColumnIndex("street")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("street"));
			business_type = cursor.getString(cursor
					.getColumnIndex("business_type")) == null ? "" : cursor
					.getString(cursor.getColumnIndex("business_type"));
			isUpload = cursor.getString(cursor.getColumnIndex("is_upload")) == null ? ""
					: cursor.getString(cursor.getColumnIndex("is_upload"));

			business.setId(id);
			business.setBusiness_name(business_name);
			business.setBusiness_type(business_type);
			business.setContacts(contacts);
			business.setData_of_issue(data_of_issue);
			business.setExpiry_data(expiry_data);
			business.setLegal_person(legal_person);
			business.setLicense_key(license_key);
			business.setOperate_addrress(operate_address);
			business.setQuality_principal(quality_principal);
			business.setRange(range);
			business.setRegister_address(register_address);
			business.setStreet(street);
			business.setBusi(busi);
			business.setIsUpload(isUpload);
			if (!("-1".equals(business.getIsUpload()))) {
				list.add(business);
			}
		}
		if (list != null && list.size() > 0) {
			llDataNum.setVisibility(View.VISIBLE);
			tvDataNum.setText("共搜索到" + list.size() + "条数据");
		} else {
			tvDataNum.setText("共搜索到0条数据");
		}
		db.close();
		cursor.close();
		return list;
	}

	// 返回键的重写
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			new AlertDialog.Builder(context)
					.setTitle("退出程序")
					.setMessage("确定退出吗？")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									AppManager.getAppManager().AppExit(context);
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {

								}
							}).show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		switch (position) {
		case 0:
			Intent intent = new Intent(context, UpLoadActivity.class);
			startActivity(intent);
			break;
		case 1:
			Intent intent1 = new Intent(context, MainActivity.class);
			startActivity(intent1);
			break;

		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!TextUtils.isEmpty(etFuzzySearch.getText().toString().trim())) {
			searchAddress(etFuzzySearch.getText().toString().trim());
		} else {
			businessList.clear();
			businessList = startSearch();
			adapter.setBusinesss(businessList);
			adapter.notifyDataSetChanged();
		}
	}

	/**
	 * 查检APP是否有新版本
	 */
	public void updateInfo() {
		String currentVersion = AppUtils.getVersionName(context);
		Log.d("tag", "当前版本是:"+currentVersion);
		
		
		
		
	}
}
